package com.hong;

import java.util.Random;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;

public class CyclicBarrierDemo2 {


    final static CyclicBarrier BARRIER = new CyclicBarrier(10, () -> {
        System.out.println("扎口袋");

    });

    static class Maize implements Runnable {
        final static AtomicInteger incr = new AtomicInteger();

        @Override

        public void run() {
            try {
                System.out.println("装" + incr.getAndIncrement() + "号玉米进口袋");

                Thread.sleep(new Random().nextInt(10) * 100);

                BARRIER.await();

            } catch (InterruptedException | BrokenBarrierException e) {
                e.printStackTrace();

            }

        }

    }

    public static void main(String[] args) {
        ExecutorService executorService = Executors.newFixedThreadPool(20);

        for (int i = 0; i < 10; i++) {
            executorService.execute(new Maize());

        }

        executorService.shutdown();

    }

}
